import 'model_base.dart';

import 'package:amap_flutter_base/amap_flutter_base.dart';

class UnitModel extends ModelBase {
  final String code;
  final String name;
  final String addr;
  final String tel;
  final String manager;
  final String policeStation;
  late final bool isJoin;
  final double? longitude;
  final double? latitude;
  final LatLng? latLng;

  // 构造函数，通过 Map 初始化
  UnitModel({
    required super.id,
    required super.createdAt,
    this.code = "编号",
    this.name = "名字",
    this.addr = "地址",
    this.tel = "电话",
    this.manager = "负责人",
    this.policeStation = "派出所",
    this.isJoin = false,
    this.longitude,
    this.latitude,
  })  : latLng = (longitude != null &&
                latitude != null &&
                longitude != 0 &&
                latitude != 0)
            ? LatLng(latitude, longitude)
            : null;

  // 工厂构造函数，通过 JSON Map 创建 Unit 实例
  factory UnitModel.fromJson(Map<String, dynamic> map) {
    return UnitModel(
      id: map["id"] ?? -1,
      createdAt: DateTime.fromMillisecondsSinceEpoch(map["createdAt"] ?? 0),
      name: map["name"] ?? "名字",
      code: map["code"] ?? "编号",
      addr: map["addr"] ?? "地址",
      tel: map["tel"] ?? "电话",
      manager: map["manager"] ?? "负责人",
      policeStation: map["policeStation"] ?? "派出所",
      isJoin: map["isJoin"] ?? false,
      longitude: map["longitude"] != null
          ? double.parse(map["longitude"].toString())
          : null,
      latitude: map["latitude"] != null
          ? double.parse(map["latitude"].toString())
          : null,
    );
  }

  // 将 Unit 实例转换为 JSON Map
  Map<String, dynamic> toJson() {
    return {
      "id": id,
      "createdAt": createdAt.millisecondsSinceEpoch,
      "name": name,
      "code": code,
      "addr": addr,
      "tel": tel,
      "manager": manager,
      "policeStation": policeStation,
      "isJoin": isJoin,
      "longitude": longitude,
      "latitude": latitude,
    };
  }

  // 静态方法，将动态数据转换为 Unit 列表
  static List<UnitModel> toList(dynamic res) {
    var data = List<Map<String, dynamic>>.from(res);
    return data.map((map) => UnitModel.fromJson(map)).toList();
  }
}
